package cn.yqn.exception;

import cn.yqn.enums.GlobalEnumCode;
import cn.yqn.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Component
@Slf4j
public class GlobalException {

    /** 
    * @Title: 全局异常处理
    * @Description: TODO
    * @Author: YQN
    * @Version: 1.0
    * @Date:  2022/8/26 11:41
    * @Parameters: [e]
    * @Return cn.yqn.result.JSONResult
    */
    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e) {
        e.printStackTrace();
        log.info("异常捕获!");
        return JSONResult.error(GlobalEnumCode.ERROR.getMessage());
    }

    /** 
    * @Title: 自定义枚举处理
    * @Description: TODO
    * @Author: YQN
    * @Version: 1.0
    * @Date:  2022/8/26 11:41
    * @Parameters: [e]
    * @Return cn.yqn.result.JSONResult
    */
    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalCustomExceptionHandler(GlobalCustomException e) {
        e.printStackTrace();
        log.info("异常捕获!" + GlobalEnumCode.ERROR.getCode());
        return JSONResult.error(e); 
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        StringBuffer stringBuffer = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(item -> stringBuffer.append(item.getDefaultMessage()).append(""));
        return JSONResult.error(stringBuffer.toString());
    }

    /** 
    * @Title: 自定义异常捕获
    * @Description: TODO
    * @Author: YQN
    * @Version: 1.0
    * @Date:  2022/9/17 13:39
    * @Parameters: [e]
    * @Return cn.yqn.result.JSONResult
    */
    @ExceptionHandler(RuntimeException.class)
    public JSONResult runtimeExceptionExceptionHandler(RuntimeException e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage());
    }

}
